<template>
    <Transition name="mask">
            <!-- 全局遮罩 -->
        <div class="oc-mask" @touchmove="demo" @touchend="end" v-if="props.show" :style="{backgroundColor:props.backgroundColor,zIndex:props.zIndex}" @click.self="close" :arial-modal="true">
            <div :style="{width:props.width}" class="oc-slot">
                <slot name="default"></slot>
            </div>
        </div>
    </Transition>
</template>

<script setup lang='ts'>
// import from "vue";
import { useScrollLock } from '@vueuse/core';
import * as vue_demi from 'vue-demi';

interface MaskProps {
    show?:boolean;
    backgroundColor?:string;
    width?:string;
    zIndex?:string;
    isLocked?:boolean;
    type?:'center'|'bottom'
}
const demo = (e:Event)=>{
  const body = document.body
  body.style.position = 'fixed'
  body.style.overflow = 'hidden'
}
const end = (e:Event)=>{
  e.stopPropagation()
  const body = document.body
  body.style.position = 'relative'
  body.style.overflow = 'auto'
}
const emits = defineEmits(["update:show"]);

const props = withDefaults(defineProps<MaskProps>(),{type:'center',show:false,backgroundColor:"rgba(0,0,0,.5)",width:"70%",zIndex:"2000",isLocked:false})


// const el = ref<HTMLElement | null>(null)
let isLocked:vue_demi.WritableComputedRef<boolean>|undefined = undefined;
onBeforeMount(()=>{
    if(props.isLocked) isLocked = useScrollLock(document.querySelector('html'));
});

onBeforeUnmount(()=>{
    if(props.isLocked && isLocked)  isLocked.value = false;
});


// 关闭遮罩层
const close = ()=>{
    emits("update:show",false)
}
const open = ()=>{
    emits("update:show",true)
}

watch(()=>props.show,()=>{
    if(props.show){
        if(props.isLocked && isLocked)  isLocked.value = false;
        document.body.style.overflow="hidden";
    }else{
        if(props.isLocked && isLocked)  isLocked.value = false;
        document.body.style.overflow="auto";
    }
})

defineExpose({
    close,
    open
})

</script>

<style lang="scss">
.oc-mask{
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    // overflow: auto;
    .oc-slot{
        position: absolute;
        transform: translateX(-50%) translateY(-50%);
        left: 50%;
        top: 50%;
        z-index: 2001;
        margin: 0 auto;
        color: #fff;
        display: flex;
        justify-content: center;
    }
}
.mask-enter-active, .mask-leave-active{
    transition: all .3s ease;
}
.mask-enter-from,.mask-leave-to{
    transform: scale(1.2);
    opacity: 0;
}
</style>
